﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using cde.UserControl;
using cde.cache;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using Cit.CDE.Net.Module;
using Cit.CDE.Net.Module.Commons;
using cde.SystemCommon;
using ConfigAndElse;
using Module;

public partial class main_comm_Wait : UserControl.MenuPathPage
{
    private CDEEntityManager moto_em;
    private CDESearchCriteria sc;
    private CDESearchCriteria scTemp;
    private string pageSize = string.Empty;
    private string pageStart = string.Empty;
    private string allSize = string.Empty;
    private string radioBtn = string.Empty;
    private string chkFlg = string.Empty;
    private Boolean chkdata = false;
    private string txtDataCount = string.Empty;
    private string moto_EM_FN = string.Empty;

    private string orderFlag = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        
        moto_EM_FN = Request.QueryString["EnFullName"];
        pageSize = Request.QueryString["PageSize"];
        pageStart = Request.QueryString["PageStart"];
        allSize = Request.QueryString["AllSize"];
        radioBtn = Request.QueryString["RadioBtn"];
        chkFlg = Request.QueryString["chkFlg"];
        txtDataCount = Request.QueryString["DataCount"];
       
        //scTemp = (CDESearchCriteria)Session[CDEConstants.CONST_SESSION_SC];

        scTemp = (CDESearchCriteria)Session[WEBConstants.SC_SESSION_ID + moto_EM_FN];

        if (moto_EM_FN == "WEB.EMAIL_ADD")
        {
            moto_EM_FN = "WEB.Email_Exc";
        }
        else if (moto_EM_FN == "WEB.ORDER_REGISTER")
        {
            moto_EM_FN = "WEB.ORDER_REGISTEREXPORT";
        }
        else if (moto_EM_FN == "WEB.SOCIAL_QUERYEXPORT")
        {
            moto_EM_FN = "WEB.SOCIAL_QUERYEXPORTLIST";
        }
        else if (moto_EM_FN == "WEB.ORDERS_MANAGER")
        {
            moto_EM_FN = "WEB.ORDER_MANAGER_OUTPUT";
            orderFlag = "ORDERS_MANAGER";
        }
        else if (moto_EM_FN == "WEB.ORDERS_INQUIRY")
        {
            moto_EM_FN = "WEB.ORDER_MANAGER_OUTPUT";            
        }
        else if (moto_EM_FN == "WEB.ORDERS_HISTORY")
        {
            moto_EM_FN = "WEB.ORDER_MANAGER_OUTPUT";
        }
        moto_em = CDEFactory.getEMByFullName(moto_EM_FN);

        sc = new CDESearchCriteria(moto_em);
        //转移查询条件
        foreach (object[] obj in scTemp.ListConditions)
        {
            sc.ListConditions.Add(obj);
        }

        foreach (string[] obj in scTemp.ListSortOders)
        {
            sc.ListSortOders.Add(obj);
        }
        sc.PageSize = scTemp.PageSize;
        sc.PageStart = scTemp.PageStart;
        
       
    }

    protected void cmdCSV_Click(object sender, EventArgs e)
    {
        this.v_hid_pageLoad.Value = "1";
        if (radioBtn == "4")
        {
            sc.PageSize = int.Parse(txtDataCount);
            sc.PageStart = 1;
        }
        else if (radioBtn == "2")
        {
            sc.PageSize = int.Parse(allSize);
            sc.PageStart = int.Parse(pageStart);
        }
        else if (radioBtn == "3")
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
            this.chkdata = true;
        }
        else
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
        }

        string templateFileName = "";
        string name="";
        if (moto_em != null)
        {

           // string x = sc.ListConditions[1].GetValue(2).ToString();
            if (moto_em.Full_Name.Equals("WEB.SOCIAL_QUERYEXPORTLIST"))
            {

                // string x = sc.ListConditions[1].GetValue(2).ToString();
                if ("0".Equals(sc.ListConditions[1].GetValue(2).ToString()))
                {
                    moto_em.Label = "单位查询导出";
                }

                else if ("1".Equals(sc.ListConditions[1].GetValue(2).ToString()))
                {
                    moto_em.Label = "住址查询导出";
                }

                else if ("2".Equals(sc.ListConditions[1].GetValue(2).ToString()))
                {
                    moto_em.Label = "简历查询导出";
                }

                else if ("3".Equals(sc.ListConditions[1].GetValue(2).ToString()))
                {
                    moto_em.Label = "银行查询导出";
                }
            }
            name=moto_em.Label;
        }

        templateFileName = System.Configuration.ConfigurationManager.AppSettings["CSV_OUT_PATH"] + name + "_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"; //"_" + languageCode + 
        templateFileName = System.Web.HttpContext.Current.Server.MapPath(templateFileName);
         
        FileInfo DownloadFile = new FileInfo(templateFileName);
        if (DownloadFile.Exists == true)
        {
            DownloadFile.Delete();
        }

        excelWrite(templateFileName);
        
        excelDownload(templateFileName);

        this.closeWindow();
    }

    protected void excelWrite(string templateFileName)
    {
        if (radioBtn == "4")
        {
            sc.PageSize = int.Parse(txtDataCount);
            sc.PageStart = int.Parse(pageStart);
        }
        else if (radioBtn == "2")
        {
            sc.PageSize = int.Parse(allSize);
            sc.PageStart = 1;
        }
        else if (radioBtn == "3")
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
            this.chkdata = true;
        } 
        else
        {
            sc.PageSize = int.Parse(pageSize);
            sc.PageStart = int.Parse(pageStart);
        }
        try
        {
            List<CDEEntity> listEntity = new List<CDEEntity>();

            if (moto_em.Full_Name == "WEB.ORDER_MANAGER_OUTPUT")
            {
                listEntity = SqlQueryEntity.sqlQueryListExc(moto_em, sc, this.orderFlag);
            }
            else
            {
                listEntity = CDEService.LoadEntities(moto_em, sc);
            }
            string[] aryChk = this.chkFlg.Split(',');
            
            if (System.IO.File.Exists(templateFileName))
            {
                System.IO.File.Delete(templateFileName);
            }

            System.Data.DataTable dt = new System.Data.DataTable();
            System.Data.DataRow dr;
            foreach (CDEAttribute cdeAttrheader in moto_em.ListAttributes)
            {   //NO_DISPLAY的不进行导出，参照类型的不进行导出
                if (cdeAttrheader.DISP_type != "N" && cdeAttrheader.P_type !="S") // && cdeAttrheader.DISP_type != "H")
                {
                    //dt.Columns.Add(new System.Data.DataColumn());
                    dt.Columns.Add(cdeAttrheader.Name);
                }
            }

            //System.Data.DataRow drName = dt.NewRow();
            System.Data.DataRow drLabel = dt.NewRow();

            int colIndex = 0;
            foreach (CDEAttribute cdeAttrheader in moto_em.ListAttributes)
            {
                if (cdeAttrheader.DISP_type != "N" && cdeAttrheader.P_type != "S") // && cdeAttrheader.DISP_type != "H")
                {
                    //drName[colIndex] = cdeAttrheader.Name;
                    drLabel[colIndex] = cdeAttrheader.Label;
                    colIndex++;
                }
            }
            //dt.Rows.Add(drName);
            dt.Rows.Add(drLabel);

            if (this.chkdata)
            {
                int rowIndex = 0;
                foreach (CDEEntity entity in listEntity)
                {
                    if (moto_EM_FN == "WEB.USER_Exc")
                    {
                        if (rowIndex >= int.Parse(pageSize))
                            break;
                    }
                    if (aryChk[rowIndex] != "0")
                    {
                        dr = dt.NewRow();
                        for (int index = 0; index < dt.Columns.Count; index++)
                        {
                            //string name = dt.Rows[0][index].ToString();
                            string name = dt.Columns[index].ToString();
                            string value = StringWithXml.getObject2String(entity.get(name));
                            CDEColumn pclm = moto_em.getAttribute(name).getP_Colmun();
                            //if (!CDEConstants.IsEmpty(entity.get(name)) && pclm.isHaveCandidate())
                            //{
                            //    dr[index] = pclm.getCandidateLable(EntityWithXml.getObject2String(entity.get(name)));
                            //}
                            //else
                            //{
                            //    dr[index] = ConstDataType.STRING.Equals(moto_em.getAttribute(name).getP_Colmun().Type) ? "'" + entity.get(name) : entity.get(name);
                            //}
                            if (value != string.Empty && pclm.isHaveCandidate())
                            {
                                List<CDECandidate> listCandidate = pclm.getCandidates();
                                foreach (CDECandidate candidate in listCandidate)
                                {
                                    if (candidate.Value == value)
                                    {
                                        dr[index] = candidate.Label;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                dr[index] = ConstDataType.STRING.Equals(moto_em.getAttribute(name).getP_Colmun().Type) ? "'" + value : entity.get(name);
                            }
                        }
                        dt.Rows.Add(dr);
                    }
                    rowIndex++;
                }
            }
            else
            {
                foreach (CDEEntity entity in listEntity)
                {
                    dr = dt.NewRow();
                    for (int index = 0; index < dt.Columns.Count; index++)
                    {
                        //string name = dt.Rows[0][index].ToString();
                        string name = dt.Columns[index].ToString();
                        string value = StringWithXml.getObject2String(entity.get(name));
                        CDEColumn pclm = moto_em.getAttribute(name).getP_Colmun();
                        //if (!CDEConstants.IsEmpty(entity.get(name)) && pclm.isHaveCandidate())
                        //{
                        //    dr[index] = pclm.getCandidateLable(EntityWithXml.getObject2String(entity.get(name)));
                        //}
                        //else
                        //{
                        //    dr[index] = ConstDataType.STRING.Equals(moto_em.getAttribute(name).getP_Colmun().Type) ? "'" + entity.get(name) : entity.get(name);
                        //}
                        if (value != string.Empty && pclm.isHaveCandidate())
                        {
                            List<CDECandidate> listCandidate = pclm.getCandidates();
                            foreach (CDECandidate candidate in listCandidate)
                            {
                                if (candidate.Value == value)
                                {
                                    dr[index] = candidate.Label;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            dr[index] = ConstDataType.STRING.Equals(moto_em.getAttribute(name).getP_Colmun().Type) ? "'" + value : entity.get(name);
                        }
                    }
                    dt.Rows.Add(dr);
                }
            }

            if (moto_EM_FN == "WEB.USER_Exc")
            {
                if (radioBtn == "1")
                {
                    dt = this.changeDT(dt);
                }
            }

            ExcelIO excelIO = new ExcelIO();
            //excelIO.writeTableDataToExcel(templateFileName, dt);
            excelIO.writeTableDataToExcel_Self(templateFileName, dt);
        }
        catch (Exception e)
        {
            UserControl.Log.SaveException(e);
        }
        finally
        {
        }
    }
    private void excelDownload(string templateFileName)
    {
        FileInfo DownloadFile = new FileInfo(templateFileName);
        if (DownloadFile.Exists == true)
        {
            Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = false;
            Encoding encodeShiftJIS = Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename="
                + HttpUtility.UrlEncode(DownloadFile.Name, encodeShiftJIS));
            Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            Response.WriteFile(DownloadFile.FullName);
            Response.Flush();
            DownloadFile.Delete();
            Response.End();
        }
    }

    private void closeWindow()
    {
        StringBuilder sbr = new StringBuilder();
        sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
        sbr.AppendFormat("window.close();{0}", Environment.NewLine);
        sbr.AppendFormat("</script>{0}", Environment.NewLine);
        Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
    }
    /// <summary>
    /// 改变查询字段
    /// </summary>
    private void changeSc() 
    {
        foreach (object[] con in sc.ListConditions) 
        {
            if (!con[0].ToString().StartsWith("A_")) { 

            con[0] = "A_" + con[0].ToString();

            }
         }
    }
    /// <summary>
    /// 修改查询结果 去除多个调查信息
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private DataTable changeDT(DataTable dt)
    {
        DataTable _dt = new DataTable();

        foreach (DataColumn dc in dt.Columns)
        {
            _dt.Columns.Add(dc.ColumnName);

        }

        int i = 0;

        foreach (DataRow row in dt.Rows)
        {
            if (i < int.Parse(pageSize) + 2)
            {
                _dt.Rows.Add(row.ItemArray);
            }
            i++;
        }

        return _dt;
    }
}
